package aryn.framework.directory;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;

public abstract class FileHandler {

	private File toWrite;
	protected BufferedReader reader = null;
	protected BufferedWriter writer = null;
	
	public final void openFile(String toRead, String toWrite) {
		try {
			this.toWrite = new File(toWrite);
			writer = new BufferedWriter(new FileWriter(toWrite));
		} catch (IOException e) {
			e.printStackTrace();
		}
		openFile(toRead);
	}
	
	public final void openFile(String path) {
		File file = new File(path);
		if (!file.isFile()) {
			System.out.println(path + " is not a valid file.");
			System.exit(1);
		}
		try {
			reader = new BufferedReader(new FileReader(path));
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		}
		
		if (file.exists())  onBeforeReading(file);
		else				System.out.println(file + "does not exist.");
		String s = null;
		try {
			while((s = reader.readLine()) != null) {
				onReading(file, s);
			}
			onAfterReading(file);
			reader.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
		
		if (writer != null)
			try {
				writer.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
	}
	
	public File getToWrite() {
		return toWrite;
	}

	protected abstract void onBeforeReading(File file);
	protected abstract void onReading(File file, String s) throws IOException;
	protected abstract void onAfterReading(File file) throws IOException;
}
